import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

const addr2line = 'E:/ndk-windows/android-ndk-r23b/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-addr2line.exe';

const input = 'D:/Program Files/Nox/bin/log.txt';
// F:\games\fysw_android_develop\export\unityLibrary\build\il2cpp_armeabi-v7a_Release\il2cpp_cache\buildstate\artifacts\objcopy_hhch
const libil2cpp_sym_so = 'C:/Users/Administrator/Desktop/libil2cpp.sym.so';

const content = fs.readFileSync(input, 'utf-8');

const parsedLines: string[] = [];
const lines = content.split(/\r?\n/);
let startParse = false;
for (const line of lines) {
    if (!line.includes('E CRASH')) continue;

    let parsed = line;
    if (line.includes('backtrace:')) {
        startParse = true;
    } else {
        if (startParse) {
            const mch = line.match(/#\d{2} pc (\w{8})  (\S+)\/libil2cpp\.so/);
            if (mch) {
                const addr = mch[1];
                const rst = execSync(`${addr2line} -C -f -e ${libil2cpp_sym_so} ${addr}`, { encoding: 'utf-8' });
                parsed = line.replace(addr, rst.split(/\r?\n/)[0]);
            }
        }
    }
    parsedLines.push(parsed);
}

const outDir = path.join(__dirname, '../tmp');
if (!fs.existsSync(outDir)) {
    fs.mkdirSync(outDir, { recursive: true });
}
fs.writeFileSync(path.join(outDir, 'out.txt'), parsedLines.join('\n'), 'utf-8');
